<template>
  <PageLayout class="p-24">
    <a-card>
      <a-descriptions title="基本信息">
        <a-descriptions-item label="代理商姓名">{{
          detail.realName
        }}</a-descriptions-item>
        <a-descriptions-item label="手机号码">{{
          detail.phone
        }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{
          detail.createTime
        }}</a-descriptions-item>

        <a-descriptions-item label="代理类型">{{
          detail.roleType == 0 ? "普通代理商" : "VIP代理商"
        }}</a-descriptions-item>
      </a-descriptions>
    </a-card>

    <a-card>
      <div class="d-flex j-sb">
        <a-descriptions title="代理门店列表"> </a-descriptions>
        <a-button type="primary" @click="visible = true">绑定</a-button>
      </div>
      <BasicTable
        ref="tableRef1"
        :query-params="{ agentId: route.query.id }"
        :apiFetch="postAgentBoundShopPage"
        :columns="columns1"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'agentRatio'">
            {{ record.agentRatio }}
            <EditOutlined @click="showRatioModal(record)" />
          </template>
          <template v-if="column.key === 'action'">
            <a class="btn" @click="remove(record.id)">解绑</a>
          </template>
        </template>
      </BasicTable>
    </a-card>
    <!-- <a-card>
      <div class="d-flex j-sb">
        <a-descriptions title="代理设备列表"> </a-descriptions>
        <a-button type="primary" @click="showDeviceBind">绑定</a-button>
      </div>
      <div class="w-100 overflow-h">
        <BasicTable
          ref="deviceTableRef"
          :query-params="{ agentId: route.query.id }"
          :apiFetch="postAgentBoundDevicePage"
          :columns="columns2"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a class="btn" @click="removeDevice(record.id)">解绑</a>
            </template>
          </template>
        </BasicTable>
      </div>
    </a-card> -->
    <!-- <a-card>
      <a-descriptions title="代理订单记录"> </a-descriptions>
      <BasicTable
        ref="financeTableRef"
        :query-params="queryData"
        :columns="columns3"
        :apiFetch="postFinancialBillOrderPage"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-space class="space-btn--box" :size="10">
              <a class="btn" @click="showDetail(record)">查看详情</a>
            </a-space>
          </template>
        </template>
      </BasicTable>
    </a-card> -->

    <!-- <a-card>
      <a-descriptions title="代理订单记录">

      </a-descriptions>
      <BasicTable
        ref="financeTableRef"
        :query-params="queryData"
        :columns="columns3"
        :apiFetch="postFinancialBillPage"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-space class="space-btn--box" :size="10">
              <a class="btn" @click="showDetail(record)">查看详情</a>
            </a-space>
          </template>
        </template>
      </BasicTable>
    </a-card> -->

    <a-card>
      <a-descriptions title="代理财务数据"> </a-descriptions>

      <div class="mb-16">
        <div class="mb-8">钱包余额：{{ detail.amount }}元</div>
        <div>
          收入明细
          <a-button type="primary" @click="importFile(1)">导出</a-button>
        </div>
      </div>
      <BasicTable
        ref="incomeTableRef"
        :query-params="queryData"
        :columns="columns4"
        :apiFetch="postAgentWalletLogPage"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-space class="space-btn--box" :size="10">
              <a class="btn" @click="showDetail(record)">查看详情</a>
            </a-space>
          </template>
        </template>
      </BasicTable>
      <div class="d-flex mb-16 mt-16">
        <div>
          提现明细
          <a-button type="primary" @click="importFile(2)">导出</a-button>
        </div>
      </div>
      <BasicTable
        ref="withdrawalTableRef"
        :query-params="queryData"
        :columns="columns5"
        :apiFetch="postAgentWithdrawPage"
      >
      </BasicTable>
    </a-card>

    <a-modal
      v-model:visible="visible"
      title="关联账号"
      :width="500"
      @ok="bindShop"
    >
      <a-select
        v-model:value="shopId"
        option-filter-prop="label"
        style="width: 100%"
        placeholder="请选择"
        show-search
        :options="shopList"
      ></a-select>
    </a-modal>

    <a-modal
      v-model:visible="deviceVisible"
      title="绑定设备"
      :width="500"
      @ok="bindDevice"
    >
      <a-select
        v-model:value="deviceFormstate.deviceId"
        style="width: 100%; margin-bottom: 20px"
        placeholder="请选择设备"
        :options="deviceList"
      ></a-select>
      <a-select
        v-model:value="deviceFormstate.deviceType"
        style="width: 100%"
        placeholder="请选择设备类型"
        :options="[
          {
            label: '开拓设备',
            value: '0',
          },
          {
            label: '关联设备',
            value: '1',
          },
        ]"
      ></a-select>
    </a-modal>
    <a-modal
      v-model:visible="visible1"
      title="修改抽成比例"
      :width="500"
      @ok="editRatio"
    >
      <a-input-number
        v-model:value="ratioMsg.agentRatio"
        placeholder="请修改"
        :precision="2"
        :step="0.01"
        style="width: 100%"
        :max="1.0"
        string-mode
      />
    </a-modal>

    <DetailModal ref="detailModalRef" :data="dataDetail"></DetailModal>
  </PageLayout>
</template>

<script setup>
import {
  postAgentDetail,
  postShopUserList,
  postAgentBoundShopPage,
  postAgentPageBindableShopList,
  postAgentBindShop,
  postAgentUpdateShopRatio,
  postShopBoundUser,
  postShopBoundUserDelete,
  postAgentUnbindShop,
  postAgentUnbindDevice,
  postAgentWalletLogExport,
  postAgentWithdrawExport,
  postAgentBindableDeviceList,
  postAgentWithdrawPage,
  postAgentWalletLogPage,
  postAgentBoundDevicePage,
  postFinancialBillOrderPage,
  postFinancialBillPage,
  postAgentBindDevice,
} from "@/api/common";
import { comfirmModal } from "@/hooks/useModal";
import DetailModal from "@/views/finance/manage/components/detail-modal.vue";
import { message } from "ant-design-vue";
import { reactive } from "vue";
const route = useRoute();
const detail = ref({});
const shopList = ref([]);
// const bindShopList = ref([]);
onMounted(() => {
  postAgentDetail({ id: route.query.id }).then((res) => {
    detail.value = res.data;
  });
  // getBindDeviceList();
  // getBoundUserList();
});
const visible = ref(false);

watch(
  () => visible.value,
  () => {
    if (visible.value) {
      postAgentPageBindableShopList().then((res) => {
        let list = res.data || [];

        shopList.value = list?.map((item) => {
          return {
            ...item,
            label: item.name,
            value: item.id,
          };
        });
      });
    }
  }
);
const deviceList = ref([]);
const deviceVisible = ref(false);
const showDeviceBind = () => {
  deviceVisible.value = true;
};
watch(
  () => deviceVisible.value,
  () => {
    if (deviceVisible.value) {
      getBindDeviceList();
    }
  }
);
// const getBoundUserList = () => {
//   postAgentBoundShopPage({ agentId: route.query.id }).then((res) => {
//     console.log('res?.data',res);
//     bindShopList.value = res?.data || [];
//   });
// };
const tableRef1 = ref(null);
const shopId = ref([]);
const bindShop = () => {
  if (shopId.value?.length) {
    postAgentBindShop({
      shopId: shopId.value,
      agentId: route.query.id,
    }).then((res) => {
      message.success("绑定成功");
      shopId.value = undefined;
      visible.value = false;
      tableRef1.value.fetch();
      // getBoundUserList();
    });
  }
};

const visible1 = ref(false);
const ratioMsg = ref({});
const showRatioModal = (record) => {
  ratioMsg.value = {
    agentId: route.query.id,
    shopId: record.id,
    agentRatio: record.agentRatio,
  };
  visible1.value = true;
};
const editRatio = () => {
  postAgentUpdateShopRatio(ratioMsg.value).then(() => {
    message.success("修改成功");
    visible1.value = false;
    tableRef1.value.fetch();
  });
};

const remove = (shopId) => {
  comfirmModal({
    content: "确认解绑该门店",
    onOk() {
      postAgentUnbindShop({ agentId: route.query.id, shopId }).then(() => {
        message.success("解绑成功");
        tableRef1.value.fetch();
        deviceTableRef.value.fetch();
      });
    },
  });
};
const deviceTableRef = ref(null);
const removeDevice = (deviceId) => {
  comfirmModal({
    content: "确认解绑该设备",
    onOk() {
      postAgentUnbindDevice({ agentId: route.query.id, deviceId }).then(() => {
        message.success("解绑成功");
        deviceTableRef.value.fetch();
      });
    },
  });
};

const deviceFormstate = reactive({
  agentId: route.query.id,
  deviceId: undefined,
  deviceType: undefined,
});

const getBindDeviceList = () => {
  postAgentBindableDeviceList({
     agentId: route.query.id,
  }).then((res) => {
    deviceList.value = res.data.map((item) => ({
      label: item.deviceSn,
      value: item.id,
    }));
  });
};

const bindDevice = () => {
  postAgentBindDevice(deviceFormstate).then((res) => {
    message.success("绑定成功");
    deviceTableRef.value.fetch();
    deviceVisible.value = false;
    deviceFormstate.deviceId = undefined;
    deviceFormstate.deviceType = undefined;
  });
};

const queryOptions = ref([
  {
    name: "",
    type: "input",
    value: "",
    placeholder: "订单号",
    filed: "orderNo",
  },

  {
    name: "订单状态",
    type: "select",
    value: [],
    placeholder: "请选择",
    filed: "statusList",
    list: [
      {
        label: "待支付",
        value: 0,
      },
      {
        label: "支付成功",
        value: 1,
      },
    ],
    attrs: { mode: "multiple" },
  },
]);
const columns1 = [
  {
    title: "序号",
    dataIndex: "index",
    width: "80px",
    customRender: (record) => `${record.index + 1}`,
  },
  {
    title: "商户名",
    dataIndex: "shopUserName",
    key: "shopUserName",
    width: "150px",
    ellipsis: true,
  },
  {
    title: "手机号码",
    dataIndex: "shopUserPhone",
    key: "shopUserPhone",
    width: "150px",
    ellipsis: true,
  },
  {
    title: "门店名",
    dataIndex: "shopName",
    key: "shopName",
    width: "150px",
    ellipsis: true,
  },
  {
    title: "设备数量",
    dataIndex: "deviceNum",
    key: "deviceNum",
    width: "150px",
    ellipsis: true,
  },
  {
    title: "抽成比例",
    dataIndex: "agentRatio",
    key: "agentRatio",
    width: "150px",
    ellipsis: true,
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: "150px",
    ellipsis: true,
  },
];
const columns2 = [
  {
    title: "序号",
    dataIndex: "index",
    width: "80px",
    customRender: (record) => `${record.index + 1}`,
  },
  {
    title: "设备编号",
    dataIndex: "deviceNo",
    key: "deviceNo",
    width: "150px",
    ellipsis: true,
  },
  {
    title: "设备机器号",
    dataIndex: "deviceSn",
    key: "deviceSn",
    width: "150px",
    ellipsis: true,
  },
  {
    title: "所属商户",
    dataIndex: "shopName",
    key: "shopName",
    width: "150px",
    ellipsis: true,
  },
  {
    title: "设备类型",
    dataIndex: "deviceType",
    key: "deviceType",
    width: "150px",
    ellipsis: true,
    customRender: ({ record }) =>
      `${record.deviceType == 0 ? "开拓设备" : "关联设备"}`,
  },
  {
    title: "设备服务次数",
    dataIndex: "serviceNum",
    key: "serviceNum",
    width: "150px",
    ellipsis: true,
  },

  {
    title: "状态",
    dataIndex: "onlineStatus",
    key: "onlineStatus",
    width: "150px",
    ellipsis: true,
    customRender: ({ record }) =>
      `${record.onlineStatus == 0 ? "在线" : "离线"}`,
  },

  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: "150px",
    ellipsis: true,
    fixed: "right",
  },
];
const columns3 = [
  {
    title: "订单编号",
    dataIndex: "orderNo",
    key: "orderNo",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "日期",
    dataIndex: "createTime",
    key: "createTime",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "信用分消耗",
    dataIndex: "amount",
    key: "amount",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "套餐类型",
    dataIndex: "packageName",
    key: "packageName",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "设备号",
    dataIndex: "deviceNo",
    key: "deviceNo",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "商户名称",
    dataIndex: "shopName",
    key: "shopName",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "订单状态",
    dataIndex: "status",
    key: "status",
    width: "180px",
    ellipsis: true,
    customRender: ({ record }) =>
      record.status == 0
        ? "使用中"
        : record.status == 1
        ? "紧急停机"
        : record.status == 2
        ? " 待评价"
        : "已完成",
  },
];
const columns4 = [
  {
    title: "门店名称",
    dataIndex: "shopName",
    key: "shopName",
    width: "180px",
    ellipsis: true,
  },

  {
    title: "充值金额",
    dataIndex: "balance",
    key: "balance",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "充值时间",
    dataIndex: "rechargeTime",
    key: "rechargeTime",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "收入金额",
    dataIndex: "amountYuan",
    key: "amountYuan",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "收入时间",
    dataIndex: "createTime",
    key: "createTime",
    width: "180px",
    ellipsis: true,
  },
];
const columns5 = [
  {
    title: "代理商名称",
    dataIndex: "agentName",
    key: "agentName",
    width: "180px",
    ellipsis: true,
  },

  {
    title: "提现时间",
    dataIndex: "withdrawTime",
    key: "withdrawTime",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "提现金额",
    dataIndex: "amountYuan",
    key: "amountYuan",
    width: "180px",
    ellipsis: true,
  },
  {
    title: "提现状态",
    dataIndex: "status",
    key: "status",
    width: "180px",
    ellipsis: true,
    customRender: ({ record }) =>
      record.status == 0
        ? "提现中"
        : record.status == 1
        ? "提现成功"
        : "提现失败",
  },
];
const detailModalRef = ref(null);
const dataDetail = ref({});
const showDetail = (record) => {
  dataDetail.value = record;
  setTimeout(() => {
    detailModalRef.value.visible = true;
  }, 0);
};

const financeTableRef = ref(null);

const incomeTableRef = ref(null);
const withdrawalTableRef = ref(null);
const queryData = reactive({
  agentId: route.query.id,
});
const onQueryDataByParams = (params) => {
  console.log("params", params);
  for (let key in params) {
    queryData[key] = params[key];
  }
  financeTableRef.value.refreshTableData();
};

const importFile = (type) => {
  const msg = {
    1: { ref: incomeTableRef.value, api: postAgentWalletLogExport },
    2: { ref: withdrawalTableRef.value, api: postAgentWithdrawExport },
  };
  if (!msg[type].ref.data?.length) {
    message.error("暂无数据");
    return;
  }
  const params = {};

  for (let key in queryData) {
    params[key] = queryData[key];
  }
  msg[type].api(params).then((res) => {
    message.success("导出成功");
  });
};
</script>

<style lang="less" scoped>
.type-list {
}
</style>
